package com.example.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;

public class TXLivePlayActivity extends AppCompatActivity implements View.OnClickListener {

    private TXCloudVideoView video_view;
    private ImageView play;
    private ImageView render_rotate;
    private ImageView render_mode;
    private ImageView ic_qcode;
    private ImageView iv_close;
    private TXLivePlayer livePlayer;
    private String url;
    private int rotateType = TXLiveConstants.RENDER_ROTATION_PORTRAIT;
    private int renderModeType = TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN;
    private boolean isPlay;
    private AlertDialog.Builder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
        localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        setContentView(R.layout.activity_t_x_live_play);
        intoView();
    }

    private void intoView() {
        video_view = findViewById(R.id.video_view);
        play = findViewById(R.id.play);
        render_rotate = findViewById(R.id.render_rotate);
        render_mode = findViewById(R.id.render_mode);
        ic_qcode = findViewById(R.id.ic_qcode);
        iv_close = findViewById(R.id.iv_close);
        play.setOnClickListener(this);
        render_rotate.setOnClickListener(this);
        render_mode.setOnClickListener(this);
        ic_qcode.setOnClickListener(this);
        iv_close.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play:
                if (isPlay) {
                    stopPlay();
                } else {
                    startPlay(url);
                }
                if (livePlayer != null) {
                    isPlay = livePlayer.isPlaying();
                }
                break;
            case R.id.render_rotate:
                if (livePlayer != null) {
                    renderRotate();
                }
                break;
            case R.id.render_mode:
                if (livePlayer != null) {
                    renderMode();
                }
                break;
            case R.id.ic_qcode:
                scanning();
                break;
            case R.id.iv_close:
                showExitInfoDialog("是否退出播放页面");
                break;
            default:
        }
    }

    /**
     * 显示确认消息
     *
     * @param msg 消息内容
     */
    public void showExitInfoDialog(String msg) {
        if (builder == null) {
            builder = new AlertDialog.Builder(this);
            builder.setCancelable(true);
        }
        builder.setTitle(msg);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        alertDialog.setCanceledOnTouchOutside(false);
    }


    /**
     * 扫描
     */
    private void scanning() {
        if (livePlayer != null && livePlayer.isPlaying()) {
            stopPlay();
            isPlay = livePlayer.isPlaying();
        }
        new IntentIntegrator(this).initiateScan();
    }

    /**
     * 识别二维码回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == IntentIntegrator.REQUEST_CODE && resultCode == RESULT_OK) {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result != null) {
                if (result.getContents() == null) {
                    Toast.makeText(this, "扫描结果为空", Toast.LENGTH_LONG).show();
                } else {
                    String str = result.getContents();
                    url = str;
//                    bitmap = createQRCodeBitmap(playUrl, 800, 800, "UTF-8", "H", "1", Color.BLACK, Color.WHITE);
//                    iv_code.setImageBitmap(bitmap);
                    Toast.makeText(this, str, Toast.LENGTH_LONG).show();
                }
            }
        }
    }


    /**
     * 切换播放器渲染模式
     */
    private void renderMode() {
        if (!livePlayer.isPlaying()) {
            Toast.makeText(this, "播放视频后再设置渲染模式", Toast.LENGTH_SHORT).show();
            return;
        }
        if (renderModeType == TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN) {
            renderModeType = TXLiveConstants.RENDER_MODE_ADJUST_RESOLUTION;
        } else {
            renderModeType = TXLiveConstants.RENDER_MODE_FULL_FILL_SCREEN;
        }
        livePlayer.setRenderMode(renderModeType);
    }

    /**
     * 切换播放器横竖屏
     */
    private void renderRotate() {
        if (!livePlayer.isPlaying()) {
            Toast.makeText(this, "播放视频后再设置横竖屏", Toast.LENGTH_SHORT).show();
            return;
        }
        if (rotateType == TXLiveConstants.RENDER_ROTATION_PORTRAIT) {
            rotateType = TXLiveConstants.RENDER_ROTATION_LANDSCAPE;
        } else {
            rotateType = TXLiveConstants.RENDER_ROTATION_PORTRAIT;
        }
        livePlayer.setRenderRotation(rotateType);
    }

    /**
     * 开始播放视频
     *
     * @param url 视频的url
     */
    private void startPlay(String url) {
        if (TextUtils.isEmpty(url)) {
            Toast.makeText(this, "播放地址不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        boolean contains = url.contains("rtmp");
        if (!contains) {
            Toast.makeText(this, "该测试包只能播放RTMP类型的流", Toast.LENGTH_SHORT).show();
            return;
        }
        if (livePlayer == null) {
            livePlayer = new TXLivePlayer(this);
            livePlayer.setPlayerView(video_view);
            livePlayer.setRenderRotation(rotateType);
            livePlayer.setRenderMode(renderModeType);
        }
        livePlayer.startPlay(url, TXLivePlayer.PLAY_TYPE_LIVE_RTMP);//播放类型为rtmp流
        play.setImageResource(R.mipmap.livepusher_pause);
    }

    /**
     * 停止视频播放
     */
    private void stopPlay() {
        if (livePlayer != null && livePlayer.isPlaying()) {
            livePlayer.stopPlay(true);
            play.setImageResource(R.mipmap.livepusher_start);
        }
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1) {
                number = 1;
            }
            return false;
        }
    });

    private int number = 1;

    @Override
    public void onBackPressed() {
        if (number == 1) {
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            number++;
            handler.sendEmptyMessageDelayed(1, 2000);
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (livePlayer != null) {
            livePlayer.stopPlay(false);
            video_view.onDestroy();
            livePlayer = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}